package houduan;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/lczmysql";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    // 静态的用户会话映射
    public static Map<Integer, User> userSessionMap = new HashMap<>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            sendErrorResponse(response, "用户名和密码不能为空", HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        try (Connection connection = getConnection();
             PreparedStatement statement = prepareLoginStatement(connection, username, password)) {

            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    Integer userId = resultSet.getInt("id");  // 从数据库中获取用户的 id
                    String dbUsername = resultSet.getString("username");  // 从数据库中获取用户名

                    // 检查用户名是否匹配
                    if (username.equals(dbUsername)) {
                        // 创建 User 对象并存入 userSessionMap
                        User user = new User(userId, dbUsername);
                        userSessionMap.put(userId, user);

                        // 将用户 ID 和用户名存入 session，以便后续请求使用
                        request.getSession().setAttribute("userSessionId", userId); // 存储用户 ID
                        request.getSession().setAttribute("username", username);     // 存储用户名

                        // 重定向到首页
                        response.sendRedirect("../index.jsp");
                    } else {
                        sendErrorResponse(response, "用户名或密码错误", HttpServletResponse.SC_UNAUTHORIZED);
                    }
                } else {
                    sendErrorResponse(response, "用户名或密码错误", HttpServletResponse.SC_UNAUTHORIZED);
                }
            }

        } catch (SQLException | ClassNotFoundException e) {
            handleException(response, e);
        }
    }

    private Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    private PreparedStatement prepareLoginStatement(Connection connection, String username, String password) throws SQLException {
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, username);
        statement.setString(2, password);
        return statement;
    }

    private void sendErrorResponse(HttpServletResponse response, String message, int statusCode) throws IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(statusCode);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(message);
        }
    }

    private void handleException(HttpServletResponse response, Exception e) throws IOException {
        sendErrorResponse(response, "服务器内部错误，请稍后再试", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        e.printStackTrace();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 可以调用 doPost 方法或者重定向到登录页面
        this.doPost(request, response);
    }
}
